package com.springsource.mvc.HandlerMappingAndHandlerAdapter;

import cn.hutool.core.collection.CollUtil;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
@ComponentScan
public class WebConfig {
    // 内嵌web容器工厂
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        return new TomcatServletWebServerFactory(8080);
    }

    // 创建DispatcherServlet
    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    // 注册DispatcherServlet，SpringMVC入口
    @Bean
    public DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) {
        DispatcherServletRegistrationBean registrationBean = new DispatcherServletRegistrationBean(dispatcherServlet, "/");
        registrationBean.setName("dispatcherServlet");
//        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    // 如果用DispatcherServlet初始化时默认添加的HandlerMapping，此时HandlerMapping会作为DispatcherServlet的变量，不会添加到容器中
    // 自己创建一个，放到容器里，可以通过getBean获取到，方便测试
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        return new RequestMappingHandlerMapping();
    }

    @Bean
    public MyRequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        MyRequestMappingHandlerAdapter handlerAdapter = new MyRequestMappingHandlerAdapter();
        TokenArgumentResolver tokenArgumentResolver = new TokenArgumentResolver();
        handlerAdapter.setCustomArgumentResolvers(CollUtil.newArrayList(tokenArgumentResolver));
        YmlReturnValueHandler ymlReturnValueHandler = new YmlReturnValueHandler();
        handlerAdapter.setCustomReturnValueHandlers(CollUtil.newArrayList(ymlReturnValueHandler));
        return handlerAdapter;
    }





}
